﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Marbles.Core.Connectors;
using System.Data;
using System.IO;
using Marbles.Core.Content.Syndication;

namespace Marbles.Core.Content.Sites
{
    public class SiteDefinition
    {

        public Int32 ExpiryHours { get { return _expiryhours; } set { _expiryhours = value; } }
        public string Title { get { return _title; } set { _title = value; } }
        public string Theme { get { return _theme; } set { _theme = value; } }
        public string SiteName { get { return _sitename; } set { _sitename = value; } }
        public string Language { get { return _Language; } set { _Language = value; } }
        public string Host { get { return _host; } set { if (value == "127.0.0.1") { _host = "localhost"; } else { _host = value; } } }
        public string SiteId { get { return _siteid; } }
        public string CopyRight { get { return _copyright; } set { _copyright = value; } }
        public string WebMaster { get { return _webmaster; } set { _webmaster = value; } }
        public string Robots { get { return _robots; } set { _robots = value; } }
        public string AnalyticsEngine { get { return _statsengine; } set { _statsengine = value; } }


        public string[] AnalyticsSettings
        {
            get
            {
                if (string.IsNullOrEmpty(_statssettings)) { return new string[] { }; }
                return _statssettings.Split(',');
            }
            set
            {
                string value1 = string.Empty;
                foreach (string s in value)
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        if (!string.IsNullOrEmpty(value1)) { value1 += ","; }
                        value1 += s;
                    }
                }
                _statssettings = value1;
            }
        }

        public bool AllowComments { get { return _allowcomments; } set { _allowcomments = value; } }
        public string ResourceDirectory
        {
            get
            {
                string ResourceDirectoryRoot = Settings.SettingsManager.ResourceDirectoryRoot;
                if (!ResourceDirectoryRoot.EndsWith("/")) { ResourceDirectoryRoot += "/"; }
                if (!_resourcedirectory.EndsWith("/"))
                {
                    return ResourceDirectoryRoot + _resourcedirectory + "/";
                }
                return ResourceDirectoryRoot + _resourcedirectory;
            }
        }
        public string TemplateDirectory
        {
            get
            {
                return Settings.SettingsManager.TemplateFolder + this.Host + "/";
            }
        }

        public string ApplicationTemplateDirectory
        {
            get
            {
                return HttpContext.Current.Server.MapPath(TemplateDirectory);
            }
        }

        public string ApplicationResourceDirectory
        {
            get
            {
                string value = HttpContext.Current.Server.MapPath(ResourceDirectory);
                return value;
            }
        }

        public string ResourceDirectory1 { get { return _resourcedirectory; } set { _resourcedirectory = value; } }

        private string _statssettings = string.Empty;
        private string _resourcedirectory = string.Empty;
        private string _robots = string.Empty;
        private bool _allowcomments = false;
        private string _title = string.Empty;
        private Int32 _expiryhours = 0;
        private string _copyright = string.Empty;
        private string _webmaster = string.Empty;
        private string _theme = string.Empty;
        private string _sitename = string.Empty;
        private string _Language = string.Empty;
        private string _host = string.Empty;
        private string _statsengine = string.Empty;
        private string _siteid = string.Empty;


        public string GetWebAnalyticsSettings(string key)
        {
            foreach (string value in this.AnalyticsSettings)
            {
                string[] args = value.Split('=');
                if (args.Length <= 1) { continue; }
                if (args[0].ToLower() == key.ToLower()) { return args[1]; }
            }
            return string.Empty;
        }

        public void SetWebAnalyticsSettings(string key, string value)
        {
            string statssettings1 = string.Empty;
            bool fnd = false;

            foreach (string setting in this.AnalyticsSettings)
            {
                string[] args = setting.Split('=');
                if (args.Length <= 0) { continue; }
                if (!string.IsNullOrEmpty(statssettings1)) { statssettings1 += ","; }
                statssettings1 += args[0] + "=";

                if (args[0].ToLower() == key.ToLower()) { statssettings1 += value.Trim(); fnd = true; } else { statssettings1 += args[1]; }
            }

            if (!fnd)
            {
                if (!string.IsNullOrEmpty(statssettings1)) { statssettings1 += ","; }
                statssettings1 += key + "=" + value;
            }

            _statssettings = statssettings1;
        }

        internal SiteDefinition(string host)
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT * FROM sites WHERE host= @host");
            cmd.AddParameter("@host", host);
            DataTable dt = dbc.FetchDataTable(cmd);
            if (dt.Rows.Count > 0)
            {
                _statssettings = dt.Rows[0]["analyticssettings"].ToString().Trim();
                _statsengine = dt.Rows[0]["analyticsengine"].ToString().ToLower();
                _allowcomments = Convert.ToBoolean(dt.Rows[0]["allowcomments"]);
                _resourcedirectory = dt.Rows[0]["resourcedirectory"].ToString();
                _Language = dt.Rows[0]["language"].ToString();
                _expiryhours = Convert.ToInt32(dt.Rows[0]["expiryhours"]);
                _title = dt.Rows[0]["title"].ToString();
                _robots = dt.Rows[0]["robots"].ToString();
                _theme = dt.Rows[0]["theme"].ToString();
                _sitename = dt.Rows[0]["sitename"].ToString();
                _webmaster = dt.Rows[0]["webmaster"].ToString();
                _copyright = dt.Rows[0]["copyright"].ToString();
                _siteid = dt.Rows[0]["siteid"].ToString();
                _host = dt.Rows[0]["host"].ToString().ToLower();
            }
        }

        internal SiteDefinition(DataRow row)
        {
            _statssettings = row["analyticssettings"].ToString().Trim();
            _statsengine = row["analyticsengine"].ToString().ToLower();
            _allowcomments = Convert.ToBoolean(row["allowcomments"]);
            _resourcedirectory = row["resourcedirectory"].ToString();
            _Language = row["language"].ToString();
            _expiryhours = Convert.ToInt32(row["expiryhours"]);
            _title = row["title"].ToString();
            _robots = row["robots"].ToString();
            _theme = row["theme"].ToString();
            _sitename = row["sitename"].ToString();
            _webmaster = row["webmaster"].ToString();
            _copyright = row["copyright"].ToString();
            _siteid = row["siteid"].ToString();
            _host = row["host"].ToString().ToLower();
        }

        public static SiteDefinition GetSiteBySiteId(string siteid)
        {
            SiteDefinition def = null;
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT * FROM sites WHERE siteid = @siteid");
            cmd.AddParameter("@siteid", siteid);
            DataTable dt = dbc.FetchDataTable(cmd);
            if (dt.Rows.Count > 0)
            {
                def = new SiteDefinition();
                def._statssettings = dt.Rows[0]["analyticssettings"].ToString().Trim();
                def._statsengine = dt.Rows[0]["analyticsengine"].ToString().ToLower();
                def._allowcomments = Convert.ToBoolean(dt.Rows[0]["allowcomments"]);
                def._resourcedirectory = dt.Rows[0]["resourcedirectory"].ToString();
                def._Language = dt.Rows[0]["language"].ToString();
                def._expiryhours = Convert.ToInt32(dt.Rows[0]["expiryhours"]);
                def._title = dt.Rows[0]["title"].ToString();
                def._robots = dt.Rows[0]["robots"].ToString();
                def._theme = dt.Rows[0]["theme"].ToString();
                def._sitename = dt.Rows[0]["sitename"].ToString();
                def._webmaster = dt.Rows[0]["webmaster"].ToString();
                def._copyright = dt.Rows[0]["copyright"].ToString();
                def._siteid = dt.Rows[0]["siteid"].ToString();
                def._host = dt.Rows[0]["host"].ToString().ToLower();
            }
            return def;
        }

        public virtual string Insert()
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("INSERT INTO sites(analyticssettings, analyticsengine, sitename, host, theme, siteid, copyright, webmaster, title, language, robots, expiryhours, resourcedirectory,allowcomments) VALUES (@analyticssettings, @analyticsengine, @sitename, @host, @theme, @siteid, @copyright, @webmaster, @title, @language, @robots, @expiryhours, @resourcedirectory,@allowcomments)");
            cmd.AddParameter("@analyticssettings", this._statssettings);
            cmd.AddParameter("@analyticsengine", AnalyticsEngine);
            cmd.AddParameter("@siteid", SiteId);
            cmd.AddParameter("@allowcomments", _allowcomments);
            cmd.AddParameter("@expiryhours", _expiryhours);
            cmd.AddParameter("@resourcedirectory", _resourcedirectory);
            cmd.AddParameter("@sitename", this._sitename);
            cmd.AddParameter("@host", this._host);
            cmd.AddParameter("@robots", _robots);
            cmd.AddParameter("@language", _Language);
            cmd.AddParameter("@theme", this._theme);
            cmd.AddParameter("@copyright", this._copyright);
            cmd.AddParameter("@webmaster", this._webmaster);
            cmd.AddParameter("@title", this._title);
            DataTable dt = dbc.FetchDataTable(cmd);
            SiteDefinition tmp = new SiteDefinition(_host);
            _siteid = tmp.SiteId;
            HttpContext.Current.Application[_host] = null;
            HttpContext.Current.Application.Remove(_host);

            CreateDirectorys(true);
            return this._siteid;
        }

        private void CreateDirectorys(bool createdefaults)
        {
            if (!Directory.Exists(ApplicationResourceDirectory))
            {
                Directory.CreateDirectory(ApplicationResourceDirectory);
            }

            if (!Directory.Exists(ApplicationTemplateDirectory))
            {
                Directory.CreateDirectory(ApplicationTemplateDirectory);
            }

            if (createdefaults)
            {
                Marbles.Core.Content.Templates.Template.CreateDefaultTemplate(this);
                Marbles.Core.Content.Templates.Template.CreateDefaultTheme(this);
            }
        }

        public virtual void Update()
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("UPDATE sites SET  analyticssettings = @analyticssettings, analyticsengine = @analyticsengine, allowcomments = @allowcomments, resourcedirectory = @resourcedirectory, expiryhours = @expiryhours, robots = @robots, language = @language, sitename = @sitename, host = @host, theme = @theme, copyright = @copyright, webmaster = @webmaster, title = @title WHERE siteid = @siteid");
            cmd.AddParameter("@analyticsengine", AnalyticsEngine);
            cmd.AddParameter("@analyticssettings", this._statssettings);
            cmd.AddParameter("@allowcomments", _allowcomments);
            cmd.AddParameter("@resourcedirectory", _resourcedirectory);
            cmd.AddParameter("@language", _Language);
            cmd.AddParameter("@robots", _robots);
            cmd.AddParameter("@expiryhours", _expiryhours);
            cmd.AddParameter("@sitename", this._sitename);
            cmd.AddParameter("@host", this._host);
            cmd.AddParameter("@theme", this._theme);
            cmd.AddParameter("@copyright", this._copyright);
            cmd.AddParameter("@webmaster", this._webmaster);
            cmd.AddParameter("@title", this._title);
            cmd.AddParameter("@siteid", this._siteid);
            dbc.ExecuteCommand(cmd);
            HttpContext.Current.Application[_host] = null;
            HttpContext.Current.Application.Remove(_host);
            CreateDirectorys(false);
        }

        public SiteDefinition()
        {
            _title = string.Empty;
            _copyright = string.Empty;
            _webmaster = string.Empty;
            _theme = string.Empty;
            _sitename = string.Empty;
            _host = string.Empty;
            _siteid = Guid.NewGuid().ToString();
        }

        public static Int32 GetSiteCount()
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT COUNT(siteid) AS sites  FROM Sites");
            DataTable dt = dbc.FetchDataTable(cmd);
            if (dt.Rows.Count <= 0) { return 0; }
            return Convert.ToInt32(dt.Rows[0]["sites"]);
        }

        public static SiteDefinition CreateNew()
        {
            SiteDefinition def = new SiteDefinition();
            return def;
        }

        public static SiteDefinition GetCurrent()
        {
            string host = HttpContext.Current.Request.Url.Host.ToLower();
            if (host == "127.0.0.1") { host = "localhost"; }
            if (host.StartsWith("www.")) { host = host.Replace("www.", ""); }
            host = host.Trim();

            SiteDefinition site = HttpContext.Current.Application[host] as SiteDefinition;

            if (site == null)
            {
                site = new SiteDefinition(host);
                HttpContext.Current.Application.Add(host, site);
            }

            return site;
        }

        public static List<IFeedItem> GetSyndicatedContent()
        {
            List<IFeedItem> items = new List<IFeedItem>();
            SiteDefinition site = GetCurrent();
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT siteid, parentpageid, templatename, allowfeeddiscovery, description, keywords, pageid, title,lastaccess, managingEditor, publishDate, syndicate, pagename FROM pages WHERE syndicate = 1 AND siteid = @siteid ORDER BY publishdate DESC");
            cmd.AddParameter("@siteid", site.SiteId);

            foreach (DataRow dr in dbc.FetchDataTable(cmd).Rows)
            {
                Pages.PageDefinition def = new Pages.PageDefinition(dr);
                items.Add(new FeedItem(def.Title, string.Format("{0}{1}/{2}{3}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, def.PageName, ".aspx"), def.Description, def.ManagingEditor, def.PublishDate));
            }
            return items;
        }

    }
}